<template>
  <div class="client-info">
    <!-- 客户信息头部 -->
    <div class="client-header">
      <div class="client-avatar">
        <img 
          :src="client?.avatar || '/default-avatar.png'" 
          :alt="client?.name || '客户'"
          @error="handleAvatarError"
        />
        <div class="status-indicator" :class="statusClass"></div>
      </div>
      
      <div class="client-basic">
        <h3 class="client-name">{{ client?.name || '未知客户' }}</h3>
        <p class="client-status">{{ statusText }}</p>
      </div>

      <div class="client-actions">
        <button 
          @click="toggleEdit" 
          class="action-btn"
          :class="{ active: isEditing }"
          title="编辑客户信息"
        >
          <i class="icon-edit"></i>
        </button>
        <button @click="showHistory" class="action-btn" title="查看历史记录">
          <i class="icon-history"></i>
        </button>
      </div>
    </div>

    <!-- 客户详细信息 -->
    <div class="client-details">
      <!-- 联系信息 -->
      <div class="info-section">
        <h4 class="section-title">联系信息</h4>
        <div class="info-list">
          <div v-if="client?.phone" class="info-item">
            <i class="icon-phone"></i>
            <span class="info-label">电话:</span>
            <span class="info-value">{{ client.phone }}</span>
            <button @click="copyToClipboard(client.phone)" class="copy-btn" title="复制">
              <i class="icon-copy"></i>
            </button>
          </div>
          
          <div v-if="client?.email" class="info-item">
            <i class="icon-email"></i>
            <span class="info-label">邮箱:</span>
            <span class="info-value">{{ client.email }}</span>
            <button @click="copyToClipboard(client.email)" class="copy-btn" title="复制">
              <i class="icon-copy"></i>
            </button>
          </div>
          
          <div v-if="client?.company" class="info-item">
            <i class="icon-company"></i>
            <span class="info-label">公司:</span>
            <span class="info-value">{{ client.company }}</span>
          </div>
          
          <div v-if="client?.position" class="info-item">
            <i class="icon-position"></i>
            <span class="info-label">职位:</span>
            <span class="info-value">{{ client.position }}</span>
          </div>
          
          <div v-if="client?.location" class="info-item">
            <i class="icon-location"></i>
            <span class="info-label">地址:</span>
            <span class="info-value">{{ client.location }}</span>
          </div>
        </div>
      </div>

      <!-- 客户标签 -->
      <div v-if="client?.tags?.length" class="info-section">
        <h4 class="section-title">
          标签
          <button v-if="isEditing" @click="showTagEditor" class="add-btn">
            <i class="icon-plus"></i>
          </button>
        </h4>
        <div class="tags-container">
          <span 
            v-for="tag in client.tags" 
            :key="tag.id"
            class="tag"
            :style="{ backgroundColor: tag.color }"
          >
            {{ tag.name }}
            <button v-if="isEditing" @click="removeTag(tag.id)" class="tag-remove">×</button>
          </span>
        </div>
      </div>

      <!-- 客户备注 -->
      <div class="info-section">
        <h4 class="section-title">备注</h4>
        <div v-if="!isEditing" class="notes-display">
          <p v-if="client?.notes" class="notes-text">{{ client.notes }}</p>
          <p v-else class="notes-empty">暂无备注</p>
        </div>
        <div v-else class="notes-editor">
          <textarea
            v-model="editingNotes"
            placeholder="添加客户备注..."
            class="notes-textarea"
            rows="4"
          ></textarea>
        </div>
      </div>

      <!-- 客户偏好设置 -->
      <div v-if="client?.preferences" class="info-section">
        <h4 class="section-title">偏好设置</h4>
        <div class="info-list">
          <div class="info-item">
            <i class="icon-language"></i>
            <span class="info-label">语言:</span>
            <span class="info-value">{{ client.preferences.preferredLanguage }}</span>
          </div>
          
          <div class="info-item">
            <i class="icon-channel"></i>
            <span class="info-label">沟通方式:</span>
            <span class="info-value">{{ getChannelText(client.preferences.communicationChannel) }}</span>
          </div>
          
          <div v-if="client.preferences.availableHours" class="info-item">
            <i class="icon-time"></i>
            <span class="info-label">可联系时间:</span>
            <span class="info-value">
              {{ client.preferences.availableHours.start }} - {{ client.preferences.availableHours.end }}
            </span>
          </div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="info-section">
        <h4 class="section-title">统计信息</h4>
        <div class="stats-grid">
          <div class="stat-item">
            <span class="stat-value">{{ client?.history?.length || 0 }}</span>
            <span class="stat-label">历史会话</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ formatDate(client?.createdAt) }}</span>
            <span class="stat-label">首次联系</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ formatDate(client?.lastContactAt) }}</span>
            <span class="stat-label">最后联系</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑模式的操作按钮 -->
    <div v-if="isEditing" class="edit-actions">
      <button @click="saveChanges" class="save-btn" :disabled="saving">
        <i v-if="saving" class="icon-loading spinning"></i>
        <span>{{ saving ? '保存中...' : '保存' }}</span>
      </button>
      <button @click="cancelEdit" class="cancel-btn">取消</button>
    </div>

    <!-- 空状态 -->
    <div v-if="!client" class="empty-state">
      <div class="empty-icon">👤</div>
      <p class="empty-text">请选择一个聊天查看客户信息</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { ClientData, Tag } from '@/types'
import { formatTimestamp } from '@/utils'
import { useClientStore } from '@/stores/client'

interface Props {
  client: ClientData | null
}

const props = defineProps<Props>()

const emit = defineEmits<{
  updateClient: [data: Partial<ClientData>]
  showHistory: [clientId: string]
  showTagEditor: []
}>()

const clientStore = useClientStore()

const isEditing = ref(false)
const saving = ref(false)
const editingNotes = ref('')

// 计算属性
const statusClass = computed(() => {
  if (!props.client) return 'offline'
  
  const lastSeen = props.client.lastContactAt || props.client.updatedAt
  const now = new Date()
  const diff = now.getTime() - lastSeen.getTime()
  const minutes = Math.floor(diff / (1000 * 60))
  
  if (minutes < 5) return 'online'
  if (minutes < 30) return 'away'
  return 'offline'
})

const statusText = computed(() => {
  if (!props.client) return '离线'
  
  const lastSeen = props.client.lastContactAt || props.client.updatedAt
  const now = new Date()
  const diff = now.getTime() - lastSeen.getTime()
  const minutes = Math.floor(diff / (1000 * 60))
  
  if (minutes < 5) return '在线'
  if (minutes < 30) return '离开'
  if (minutes < 60) return `${minutes}分钟前在线`
  
  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}小时前在线`
  
  const days = Math.floor(hours / 24)
  return `${days}天前在线`
})

// 方法
const toggleEdit = () => {
  if (isEditing.value) {
    cancelEdit()
  } else {
    startEdit()
  }
}

const startEdit = () => {
  isEditing.value = true
  editingNotes.value = props.client?.notes || ''
}

const cancelEdit = () => {
  isEditing.value = false
  editingNotes.value = ''
}

const saveChanges = async () => {
  if (!props.client) return
  
  try {
    saving.value = true
    
    const updates: Partial<ClientData> = {
      notes: editingNotes.value.trim()
    }
    
    emit('updateClient', updates)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    isEditing.value = false
  } catch (err) {
    console.error('Failed to save client changes:', err)
  } finally {
    saving.value = false
  }
}

const showHistory = () => {
  if (props.client) {
    emit('showHistory', props.client.id)
  }
}

const showTagEditor = () => {
  emit('showTagEditor')
}

const removeTag = (tagId: string) => {
  if (!props.client) return
  
  const updatedTags = props.client.tags.filter(tag => tag.id !== tagId)
  emit('updateClient', { tags: updatedTags })
}

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    // TODO: 显示复制成功提示
    console.log('Copied to clipboard:', text)
  } catch (err) {
    console.error('Failed to copy to clipboard:', err)
  }
}

const handleAvatarError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/default-avatar.png'
}

const getChannelText = (channel: string): string => {
  const channelMap: Record<string, string> = {
    chat: '在线聊天',
    email: '邮件',
    phone: '电话'
  }
  return channelMap[channel] || channel
}

const formatDate = (date?: Date): string => {
  if (!date) return '-'
  return formatTimestamp(date)
}

// 监听客户变化，重置编辑状态
watch(() => props.client, () => {
  cancelEdit()
})
</script>

<style scoped>
.client-info {
  width: 300px;
  background: var(--color-surface);
  border-left: 1px solid var(--color-border);
  display: flex;
  flex-direction: column;
  height: 100%;
}

.client-header {
  padding: 20px;
  border-bottom: 1px solid var(--color-border);
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.client-avatar {
  position: relative;
  flex-shrink: 0;
}

.client-avatar img {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.status-indicator {
  position: absolute;
  bottom: 2px;
  right: 2px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 2px solid var(--color-surface);
}

.status-indicator.online {
  background: var(--color-success);
}

.status-indicator.away {
  background: var(--color-warning);
}

.status-indicator.offline {
  background: var(--color-text-secondary);
}

.client-basic {
  flex: 1;
  min-width: 0;
}

.client-name {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.client-status {
  margin: 0;
  font-size: 12px;
  color: var(--color-text-secondary);
}

.client-actions {
  display: flex;
  gap: 4px;
}

.action-btn {
  width: 28px;
  height: 28px;
  border: none;
  background: transparent;
  color: var(--color-text-secondary);
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.action-btn:hover {
  background: var(--color-hover);
  color: var(--color-primary);
}

.action-btn.active {
  background: var(--color-primary);
  color: white;
}

.client-details {
  flex: 1;
  overflow-y: auto;
  padding: 0 20px 20px;
}

.info-section {
  margin-bottom: 24px;
}

.section-title {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--color-text);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.add-btn {
  width: 20px;
  height: 20px;
  border: none;
  background: var(--color-primary);
  color: white;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
}

.info-item i {
  width: 16px;
  color: var(--color-text-secondary);
  flex-shrink: 0;
}

.info-label {
  color: var(--color-text-secondary);
  min-width: 40px;
}

.info-value {
  color: var(--color-text);
  flex: 1;
  word-break: break-all;
}

.copy-btn {
  width: 16px;
  height: 16px;
  border: none;
  background: transparent;
  color: var(--color-text-secondary);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  transition: all 0.2s;
}

.copy-btn:hover {
  background: var(--color-hover);
  color: var(--color-primary);
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  color: white;
  font-weight: 500;
}

.tag-remove {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 14px;
  line-height: 1;
  padding: 0;
  margin-left: 2px;
}

.notes-display {
  font-size: 13px;
}

.notes-text {
  margin: 0;
  color: var(--color-text);
  line-height: 1.4;
  white-space: pre-wrap;
}

.notes-empty {
  margin: 0;
  color: var(--color-text-secondary);
  font-style: italic;
}

.notes-editor {
  margin-top: 8px;
}

.notes-textarea {
  width: 100%;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  padding: 8px;
  font-size: 13px;
  color: var(--color-text);
  background: var(--color-background);
  resize: vertical;
  min-height: 60px;
}

.notes-textarea:focus {
  outline: none;
  border-color: var(--color-primary);
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
}

.stat-item {
  text-align: center;
  padding: 12px;
  background: var(--color-background);
  border-radius: 6px;
}

.stat-value {
  display: block;
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 11px;
  color: var(--color-text-secondary);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.edit-actions {
  padding: 16px 20px;
  border-top: 1px solid var(--color-border);
  display: flex;
  gap: 8px;
}

.save-btn,
.cancel-btn {
  flex: 1;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  transition: all 0.2s;
}

.save-btn {
  background: var(--color-primary);
  color: white;
}

.save-btn:hover:not(:disabled) {
  background: var(--color-primary-dark);
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.cancel-btn {
  background: var(--color-border);
  color: var(--color-text);
}

.cancel-btn:hover {
  background: var(--color-hover);
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  color: var(--color-text-secondary);
  padding: 40px 20px;
}

.empty-icon {
  font-size: 48px;
  opacity: 0.5;
}

.empty-text {
  text-align: center;
  font-size: 14px;
  line-height: 1.4;
}

.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 图标样式 */
.icon-edit::before { content: '✏️'; }
.icon-history::before { content: '📋'; }
.icon-phone::before { content: '📞'; }
.icon-email::before { content: '📧'; }
.icon-company::before { content: '🏢'; }
.icon-position::before { content: '💼'; }
.icon-location::before { content: '📍'; }
.icon-language::before { content: '🌐'; }
.icon-channel::before { content: '💬'; }
.icon-time::before { content: '⏰'; }
.icon-plus::before { content: '+'; }
.icon-copy::before { content: '📋'; }
.icon-loading::before { content: '⟳'; }

/* 滚动条样式 */
.client-details::-webkit-scrollbar {
  width: 4px;
}

.client-details::-webkit-scrollbar-track {
  background: transparent;
}

.client-details::-webkit-scrollbar-thumb {
  background: var(--color-border);
  border-radius: 2px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .client-info {
    width: 280px;
  }
}

@media (max-width: 768px) {
  .client-info {
    position: fixed;
    top: 0;
    right: 0;
    width: 100%;
    max-width: 320px;
    z-index: 1000;
    box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  }
}
</style>